package com.dmpb.swyx.convertors;

import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import com.dmpb.swyx.convertors.utility.HttpsHandler;
import org.apache.commons.io.FilenameUtils;
import org.apache.pdfbox.exceptions.CryptographyException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.poi.hwpf.HWPFDocumentCore;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.converter.WordToHtmlUtils;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.fit.pdfdom.PDFDomTree;
import org.w3c.dom.Document;
/**
 * @author Kurra Raghu
 *
 */
public final class Convertor {

	private Convertor() {

	}

	public static void writeFile(String html, String path, String fileNname){
		try {
			File file = new File(path + fileNname);
			// if file doesnt exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}

			FileWriter fw = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(html);
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @author Kurra Raghu
	 * @param docxFilePath
	 * @return HTMLString
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static String convertDocxToHTML(String docxFilePath) throws FileNotFoundException, IOException {
		ByteArrayOutputStream out = null;
		String docxHtml = null;
		try {
			XWPFDocument document = new XWPFDocument(getFileInputStream(docxFilePath));
			XHTMLOptions options = XHTMLOptions.create();// .indent( 4 );
            options.setIgnoreStylesIfUnused(false);
			// Extract image
			//File imageFolder = new File(imgLocation);
			//options.setExtractor(new FileImageExtractor(imageFolder));
			// URI resolver
			//options.URIResolver(new FileURIResolver(imageFolder));
			out = new ByteArrayOutputStream();
			XHTMLConverter.getInstance().convert(document, out, options);
			docxHtml = new String(out.toByteArray());
			FileOutputStream fos = new FileOutputStream(new File("/Users/zhangqiang/Documents/myFile.doc"));
			out.writeTo(fos);
		} finally {
			if (out != null) {
				out.close();
			}
		}
		return docxHtml;
	}


    /**
     * @author zhangqiang
     * @param docxFilePath
     * @return HTMLString
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static String convertDocxToHTML(String docxFilePath,String newPath,String newFileName,String imgRootDirName,String imgLocation,String webRootURI) throws Exception {
        ByteArrayOutputStream out = null;
        String docxHtml = null;
        try {
            XWPFDocument document = new XWPFDocument(getFileInputStream(docxFilePath));

			List<XWPFParagraph> paragraphs = document.getParagraphs();
			List<XWPFPictureData> pictures = document.getAllPictures();


            for(XWPFPictureData xwpfPictureData : pictures){
                String partName = xwpfPictureData.getPackagePart().getPartName().getName();
                File picture = new File(imgRootDirName + imgLocation + "/" + partName);
                if(!picture.getParentFile().exists()){
                    picture.getParentFile().mkdirs();
                }
                if(!picture.exists()){
                    picture.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(picture);

                fos.write(xwpfPictureData.getData());
                fos.close();
            }

			XHTMLOptions options = XHTMLOptions.create();// .indent( 4 );
            imgLocation = new String(imgLocation.getBytes(),"utf-8");
             // Extract image
             File imageFolder = new File(webRootURI + imgLocation);
             options.setExtractor(new FileImageExtractor(imageFolder));
             // URI resolver
             options.URIResolver(new FileURIResolver(imageFolder));

            out = new ByteArrayOutputStream();
            XHTMLConverter.getInstance().convert(document, out, options);
            docxHtml = new String(out.toByteArray(),"GBK");
            FileOutputStream fos = new FileOutputStream(new File(newPath + newFileName));
            out.writeTo(fos);





        } finally {
            if (out != null) {
                out.close();
            }
        }
        return docxHtml;
    }



    /**
     * @author zhangqiang
     * @param pdfFilePath
     * @return HTMLString
     * @throws IOException
     * @throws ParserConfigurationException
     * @throws TransformerException
     * @throws CryptographyException
     */
    public static String convertPDFToHTML(String pdfFilePath,String newPath,String newFileName) throws IOException, ParserConfigurationException, TransformerException, CryptographyException {
        ByteArrayOutputStream out = null;
        String pdfHtml = null;
        try {
            PDDocument pdf = PDDocument.load(getFileInputStream(pdfFilePath));
            if (pdf.isEncrypted()) {
                pdf.decrypt("");
            }
            // create the DOM parser
            PDFDomTree parser = new PDFDomTree();
            parser.setDisableImageData(true);
            // parse the file
            parser.processDocument(pdf);
            // get the DOM Document
            Document htmlDocument = parser.getDocument();

            DOMSource domSource = new DOMSource(htmlDocument);
            out = new ByteArrayOutputStream();
            StreamResult streamResult = new StreamResult(out);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer serializer = tf.newTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty(OutputKeys.METHOD, "html");
            serializer.transform(domSource, streamResult);
            pdfHtml = new String(out.toByteArray());
            FileOutputStream fos = new FileOutputStream(new File(newPath + newFileName));
            out.writeTo(fos);
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return pdfHtml;
    }



	/**
	 * @author Kurra Raghu
	 * @param fileUrlorPath
	 * @return InputStream
	 * @throws FileNotFoundException
	 */
	private static InputStream getFileInputStream(String fileUrlorPath) throws FileNotFoundException {
		try {
			URL url = new URL(fileUrlorPath);
			return url.openConnection().getInputStream();
		} catch (Exception e) {
			try {
				//Disable HTTPS and get Response
				URL url = new URL(fileUrlorPath);
				return HttpsHandler.getInputStream(url);
			} catch (Exception e1) {
				//If fileUrlorPath is Not a usl path and is a file location path
				return new FileInputStream(fileUrlorPath);
			}
		}
	}

	/**
	 * @author zhangqiang
	 * @param file
	 * @return InputStream
	 * @throws Exception
	 */
	private static InputStream getFileInputStream(File file) throws Exception {
		return new FileInputStream(file);

	}

	public static void main(String[] args) throws Exception {
		//System.out.println(Convertor.convertDocxToHTML("/Users/zhangqiang/Documents/生物医学2016需求v1.0/资料/兼职教授.docx","/Users/zhangqiang/Desktop/test","test.html","/Users/zhangqiang/Desktop/test"));
	}

}
